<?php

namespace app\api\validate;

use think\Validate;

/**
 * 招募验证类
 */
class RecruitValidate extends Validate
{
    protected $regex = ['phone' => '/^1[3456789]\d{9}|([0-9]{3,4}-)?[0-9]{7,8}$/'];

    protected $rule = [
        'real_name' => 'require|max:25',
        'mobile' => 'require|regex:phone',
        'province' => 'require',
        'city' => 'require',
        'district' => 'require',
        'address' => 'require',
        'card_no' => 'require|checkIdCard',
        'gender' => 'require',

    ];

    protected $message = [
        'real_name.require' => '联系人必须填写',
        'real_name.max' => '联系人最多不能超过25个字符',
        'phone.require' => '手机号必须填写',
        'phone.regex' => '手机号格式错误',
        'province.require' => '省必须填写',
        'city.require' => '市名称必须填写',
        'district.require' => '区/县名称必须填写',
        'address.require' => '详细地址必须填写',
        'card_no.require' => '身份证号必须填写',
        'gender.require' => '性别必须填写',

    ];

    protected $scene = [
        'rider' => ['real_name', 'mobile', 'card_no', 'address'],
        'recycle' => ['real_name', 'mobile', 'card_no', 'address'],
        'agent' => ['real_name', 'mobile', 'gender', 'address'],
        'merchant' => ['real_name', 'mobile', 'card_no', 'address'],
        'home' => ['real_name', 'mobile', 'card_no', 'address'],
    ];

    // 验证身份证号
    protected function checkIdCard($value, $rule, $data = [])
    {
        //校验身份证位数和出生日期部分
        $pattern = "/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/";
        preg_match($pattern, $value, $match);
        $result = $match ? true : false;
        if (!$result) {
            return '请填写正确的身份证号';
        }
        //校验前两位是否是所有省份代码
        $province_code = ['11', '12', '13', '14', '15', '21', '22', '23', '31', '32', '33', '34', '35', '36', '37', '41', '42', '43', '44', '45', '46', '50', '51', '52', '53', '54', '61', '62', '63', '64', '65', '71', '81', '82', '91'];
        if (!in_array(substr($value, 0, 2), $province_code)) {
            return '请填写正确的身份证号';
        }
        //校验身份证最后一位
        $ahead17_char = substr($value, 0, 17);
        $last_char = substr($value, -1);
        $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); // 前17位的权重
        $c = array(1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2); //模11后的对应校验码
        $t_res = 0;
        for ($i = 0; $i < 17; $i++) {
            $t_res += intval($ahead17_char[$i]) * $factor[$i];
        }
        $calc_last_char = $c[$t_res % 11];
        if ($last_char != $calc_last_char) {
            return '请填写正确的身份证号';
        }
        return true;
    }

}